//
//  LXMotionAction.m
//  LXLocationRelated
//
//  Created by Livespro on 2017/10/19.
//  Copyright © 2017年 Livesxu. All rights reserved.
//

#import "LXMotionAction.h"

#import "LXHandleDatas.h"

#define kMotionStart @"MotionStartNotification"

#define kMotionStop  @"MotionStopNotification"

@implementation LXMotionAction

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kMotionStart object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kMotionStop object:nil];
}

+ (instancetype)shareMotion{
    
    static LXMotionAction *motion = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        motion = [[LXMotionAction alloc]init];
        
    });
    return motion;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(start) name:kMotionStart object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stop) name:kMotionStop object:nil];
    }
    return self;
}

- (CMMotionManager *)motionManager {
    if (!_motionManager) {
        _motionManager = [[CMMotionManager alloc] init];
        _motionManager.deviceMotionUpdateInterval = 0.2;
    }
    return _motionManager;
}

- (BOOL)isRunning {
    return _motionManager.isDeviceMotionActive;
}

- (void)start{
    if (!self.motionManager.deviceMotionAvailable) {
        return;
    }
    
    if (self.motionManager.isDeviceMotionActive) {
        return;
    }
    __weak typeof(self) weakSelf = self;
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [self.motionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXArbitraryCorrectedZVertical toQueue:queue withHandler:^(CMDeviceMotion *motion, NSError *error) {
        if (error) {
            return ;
        }
        
        [[LXHandleDatas shareHandle] handleMotionInfoMotion:motion];
        
        if (weakSelf.motionBlock) {
            
            weakSelf.motionBlock(motion);
        }
    }];
}

- (void)stop {
    if (_motionManager.isDeviceMotionActive) {
        [_motionManager stopDeviceMotionUpdates];
    }
}

@end
